package com.gxp.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gxp.mapper.AuthorityMapper;
import com.gxp.mapper.RoleMapper;
import com.gxp.pojo.Authority;
import com.gxp.pojo.Role;
import com.gxp.service.RoleService;
import com.gxp.util.common.GXPUtil;

@Service
public class RoleServiceImpl implements RoleService {
	
	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private AuthorityMapper authMapper;

	@Override
	public List<Role> findAllIntRole() {
		return findAllRole(Role.INTERNAL_ROLE_TYPE);
	}
	
	@Override
	public List<Role> findAllExtRole() {
		return findAllRole(Role.EXTERNAL_ROLE_TYPE);
	}

	@Override
	public Role findById(int roleId) {
		
		Role role = roleMapper.findById(roleId);
		if (role != null) {
			List<Authority> authList = authMapper.findByRole(role);
			if (authList != null) {
				role.setPermissionList(authList);
			}
		}
		return role;
	}

	private List<Role> findAllRole(String roleType) {
		List<Role> roleList = roleMapper.findAllRole(roleType);
		for (Role role : roleList) {
			List<Authority> authList = authMapper.findByRole(role);
			if (authList != null) {
				role.setPermissionList(authList);
			}
		}
		return roleList;
	}

	@Override
	@Transactional
	public void updateRoleAuthRelation(int roleId, int[] authArr) {
		roleMapper.delRoleAuthRelation(roleId);
		for (int authId : authArr) {
			roleMapper.insRoleAuthRelation(roleId, authId);
		}
	}
	
	@Override
	@Transactional
	public void updateUserRole(String userId, List<Integer> selectedRoleList) {
		roleMapper.delUserRole(userId);
		if (!GXPUtil.isEmpty(selectedRoleList)) {
			for (int roleId : selectedRoleList) {
				roleMapper.insUserRole(userId, roleId);
			}
		}
		
	}
	

}
